<?php

namespace App\Http\Controllers\Counter;

use App\Enums\OrderFrom;
use App\Enums\OrderItemType;
use App\Enums\OrderType;
use App\Enums\PayChannel;
use App\Enums\TradeStatus;
use App\Helper\ApiResponseHelper;
use App\Http\Controllers\Controller;
use App\Http\Requests\Counter\HandoverRequest;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class HandoverController extends Controller
{
    public function getHandover()
    {
        $user = Auth::user();
        return ApiResponseHelper::json(
            $this->getHandoverData() + [
                'user' => $user,
                'counter_work_start_at' => $user->counter_work_start_at
            ]
        );
    }

    public function getHandoverBill()
    {
        /**
         * @var User $user
         */
        $user = Auth::user();
        $store = $user->store;
        $handoverDate = now();
        //客单总数
        $orderCount = Order::where([
            'store_id' => $store->id,
            'user_id' => $user->id,
            'status' => TradeStatus::Payed,
            'from' => OrderFrom::Counter
        ])->count();
        //总营业额
        $totalMoney = Order::where([
            'store_id' => $store->id,
            'user_id' => $user->id,
            'status' => TradeStatus::Payed,
            'from' => OrderFrom::Counter
        ])->sum('money');
        //会员卡充值
        $memberRechargeMoney = Order::where([
            'store_id' => $store->id,
            'user_id' => $user->id,
            'status' => TradeStatus::Payed,
            'type' => OrderType::MemberRecharge,
            'from' => OrderFrom::Counter
        ])->sum('money');
        //退款总额
        $refundMoney = 0; //TODO: refundMoney
        //订单id
        $orderIds = Order::where([
            'store_id' => $store->id,
            'user_id' => $user->id,
            'status' => TradeStatus::Payed,
            'from' => OrderFrom::Counter
        ])->pluck('id')->toArray();
        //商品总额
        $goodsMoney = OrderItem::whereIn('order_id', $orderIds)->where('type', OrderItemType::Goods)->sum('money');
        //乐刷总额
        $leshuaMoney = Order::where([
            'store_id' => $store->id,
            'user_id' => $user->id,
            'status' => TradeStatus::Payed,
            'pay_channel' => PayChannel::LeShua,
            'from' => OrderFrom::Counter
        ])->sum('money');
        //美团总额
        $meituanMoney = Order::where([
            'store_id' => $store->id,
            'user_id' => $user->id,
            'status' => TradeStatus::Payed,
            'pay_channel' => PayChannel::MeiTuan,
            'from' => OrderFrom::Counter
        ])->sum('money');
        //抖音总额
        $douyinMoney = Order::where([
            'store_id' => $store->id,
            'user_id' => $user->id,
            'status' => TradeStatus::Payed,
            'pay_channel' => PayChannel::DouYin,
            'from' => OrderFrom::Counter
        ])->sum('money');

        //所有商品item
        $goodsItems = OrderItem::with([
            'goods', 'table.tableType', 'costRule', 'assistantUser',
        ])->whereIn('order_id', $orderIds)->where('type', OrderItemType::Goods)->get();

        return ApiResponseHelper::json([
            'order_count' => $orderCount,
            'total_money' => $totalMoney,
            'member_recharge_money' => $memberRechargeMoney,
            'refund_money' => $refundMoney,
            'goods_money' => $goodsMoney,
            'leshua_money' => $leshuaMoney,
            'meituan_money' => $meituanMoney,
            'douyin_money' => $douyinMoney,
            'goods_items' => $goodsItems,
            'handover_date' => $handoverDate->format('Y-m-d H:i:s'),
            'user' => $user,
            'counter_work_start_at' => $user->counter_work_start_at
        ]);
    }

    public function handover(HandoverRequest $request)
    {
        DB::transaction(function () use ($request) {

            $data = $this->getHandoverData();
            $cashKeep = $request->input('cash_keep');

            $cash = 0;
            $leshua = 0;
            $member = 0;
            $bad = 0;
            foreach ($data['all'] as $item) {

                switch ($item['pay_type']) {
                    case PayChannel::Member->value:
                        $member += $item['money'];
                        break;
                    case PayChannel::Cash->value:
                        $cash += $item['money'];
                        break;
                    case PayChannel::LeShua->value:
                        $leshua += $item['money'];
                        break;
                    case PayChannel::Bad->value:
                        $bad += $item['money'];
                        break;
                }
            }

            $user = Auth::user();
            $user->counterEndWork();
            $user->handovers()->create([
                'store_id' => $user->store_id,
                'cash' => $cash,
                'leshua' => $leshua,
                'bad' => $bad,
                'member' => $member,
                'cash_keep' => $cashKeep
            ]);

            //设置handover标记
            Order::where([
                'user_id' => $user->id,
                'status' => TradeStatus::Payed,
                'handover' => false,
                'from' => OrderFrom::Counter
            ])->update([
                'handover' => true
            ]);
        });

        return ApiResponseHelper::json([]);
    }

    private function getHandoverData()
    {
        $sells = [];
        $recharges = [];
        $all = [];
        $user = Auth::user();

        foreach (PayChannel::cases() as $payChannel) {

            //后台支付无需显示跳过
            if ($payChannel == PayChannel::System)
                continue;

            $sellMoney = Order::where([
                'user_id' => $user->id,
                'store_id' => $user->store_id,
                'status' => TradeStatus::Payed,
                'pay_channel' => $payChannel,
                'handover' => false,
                'type' => OrderType::Counter,
                'from' => OrderFrom::Counter
            ])->sum('money');

            if ($payChannel != PayChannel::Member) {

                $rechargeMoney = Order::where([
                    'user_id' => $user->id,
                    'store_id' => $user->store_id,
                    'status' => TradeStatus::Payed,
                    'pay_channel' => $payChannel,
                    'handover' => false,
                    'type' => OrderType::MemberRecharge,
                    'from' => OrderFrom::Counter
                ])->sum('money');

                $recharges[] = [
                    'pay_type' => $payChannel->value,
                    'pay_type_label' => $payChannel->label(),
                    'money' => $rechargeMoney
                ];
            }

            $sells[] = [
                'pay_type' => $payChannel->value,
                'pay_type_label' => $payChannel->label(),
                'money' => $sellMoney
            ];
            $all[] = [
                'pay_type' => $payChannel->value,
                'pay_type_label' => $payChannel->label(),
                'money' => $sellMoney + ($rechargeMoney ?? 0)
            ];
        }

        return [
            'sells' => $sells,
            'recharges' => $recharges,
            'all' => $all
        ];
    }
}
